package org.gc.amino.universe;

import java.util.Deque;
import java.util.LinkedList;

public class MetaUniverseCache {
	private int cache_size;
	private Deque<MetaUniverseTreeNode> deque;
	
	public MetaUniverseCache(int cache_size) {
		this.cache_size = cache_size;
		
		this.deque = new LinkedList<MetaUniverseTreeNode>();
	}
	
	public boolean has(MetaUniverseTreeNode tree_node) {
		return this.deque.contains(tree_node);
	}
	
	
	/** 
	 * Puts element int cache with optimal priority.
	 *  May remove elements with lower priority. 
	 */
	public void push(MetaUniverseTreeNode tree_node) {
		
		//If element already exists
		if(this.deque.contains(tree_node)) {
			deque.remove(tree_node);
			deque.addFirst(tree_node);
		}
		// If cache is not yet full
		else if(this.deque.size() < this.cache_size) {
			this.deque.addFirst(tree_node);
		}
		// If it is
		else {
			// The whole point of the cache is to avoid storing every possible universe
			this.deque.peekLast().removeUniverse();
			this.deque.removeLast();
			this.deque.addFirst(tree_node);
		}
	}
	
	/** 
	 * Just like @see{MetaUniverseCache.push} except the element
	 *  is known to be in the cache already. 
	 */
	public void promote(MetaUniverseTreeNode tree_node) {
		deque.remove(tree_node);
		deque.addFirst(tree_node);
	}
}
